package com.tanhua.manage.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.db.UserStatusInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.MovementsVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserStatusInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.PublishApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.manage.utils.RelativeDateFormat;
import org.apache.dubbo.config.annotation.Reference;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserService {
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private VideoApi videoApi;
    @Reference
    public PublishApi publishApi;
    @Reference
    private CommentApi commentApi;
    @Reference
    private UserStatusInfoApi userStatusInfoApi;

    /**
     * 接口名称：用户数据翻页
     */
    public ResponseEntity<Object> findByPage(Integer page, Integer pagesize) {
        // 调用Api服务，查询用户信息
        IPage<UserInfo> iPage = userInfoApi.findByPage(page, pagesize);
        // 封装分页对象
        PageResult pageResult = new PageResult(page, pagesize, (int) iPage.getTotal(), iPage.getRecords());
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：用户基本资料
     */
    public ResponseEntity<Object> findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 接口名称：用户冻结
     */
    public ResponseEntity<Object> userFreeze(Map<String, Object> map) {
        Integer userId = (Integer) map.get("userId");
        String freezingTime = (String) map.get("freezingTime");
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        System.out.println("当前日期:"+sf.format(c.getTime()));
        String timeFrame =null;
        if (freezingTime.equals("1")){
            c.add(Calendar.DAY_OF_MONTH, 3);
            timeFrame = sf.format(c.getTime());
        }else if (freezingTime.equals("2")){
            c.add(Calendar.DAY_OF_MONTH, 7);
            timeFrame = sf.format(c.getTime());
        }else if (freezingTime.equals("3")){
            timeFrame = "永久";
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId.longValue());
        userInfo.setUserStatus("2");
        userInfoApi.update(userInfo);
        String freezingRange = (String) map.get("freezingRange");
        String reasonsForFreezing = (String) map.get("reasonsForFreezing");
        String frozenRemarks = (String) map.get("frozenRemarks");
        UserStatusInfo userStatusInfo = new UserStatusInfo(userId,"2", freezingTime,timeFrame, freezingRange, reasonsForFreezing, frozenRemarks,null);
        if (userStatusInfoApi.select(userId)==null){
            userStatusInfoApi.saveStatus(userStatusInfo);
        }else {
            userStatusInfoApi.update(userStatusInfo);
        }
        String message = "成功";
        return ResponseEntity.ok(message);
    }

    /**
     * 接口名称：用户解冻
     */
    public ResponseEntity<Object> userUnfreeze(Map<String, Object> map) {
        Integer userId = (Integer) map.get("userId");
        String reasonsForThawing = (String) map.get("reasonsForThawing");
        String frozenRemarks = (String) map.get("frozenRemarks");

        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId.longValue());
        userInfo.setUserStatus("1");
        userInfoApi.update(userInfo);

        UserStatusInfo userStatusInfo = new UserStatusInfo();
        userStatusInfo.setUserId(userId);
        userStatusInfo.setUserStatus("1");
        userStatusInfo.setReasonsForThawing(frozenRemarks);
        userStatusInfoApi.update(userStatusInfo);
        String message = "成功";
        return ResponseEntity.ok(message);
    }

    /**
     * 接口名称：视频记录翻页
     */
    public ResponseEntity<Object> videoList(Long uid, Integer page, Integer pagesize) {
        //1. 调用Api分页查询
        PageResult pageResult = videoApi.findByPage(page, pagesize, uid);
        //2. 获取小视频集合
        List<Video> videoList = (List<Video>) pageResult.getItems();
        //3. 封装vo
        List<VideoVo> voList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(videoList)) {
            for (Video video : videoList) {
                //3.1 创建vo、封装vo
                VideoVo vo = new VideoVo();
                vo.setId(video.getId().toString());

                // 根据用户id查询
                UserInfo userInfo =
                        userInfoApi.findById(video.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                }
                // 封装vo: video--->vo
                BeanUtils.copyProperties(video, vo);
                // 封装vo的其他属性（没有与Video对应上的）
                vo.setCover(video.getPicUrl());
                vo.setSignature(video.getText());
                vo.setHasFocus(0);
                vo.setHasLiked(0);

                //3.2 添加到集合
                voList.add(vo);
            }
        }
        //4. 把封装好的vo集合设置到分页对象中、返回
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：动态分页
     */

    public ResponseEntity<Object> findPublishList(Integer page, Integer pagesize, Long userId, String state) {
        //1. 调用api，分页查询动态
        if (userId==0)userId=null;
        PageResult pageResult = publishApi.findByPage(page, pagesize, userId, state);
        //获取查询的动态列表
        List<Publish> publishList = (List<Publish>) pageResult.getItems();
        //创建vo集合、封装返回结果
        List<MovementsVo> voList = new ArrayList<>();
        if (publishList!=null && publishList.size()>0) {
            for (Publish publish : publishList) {
                // 创建并封装vo对象
                MovementsVo vo = new MovementsVo();
                // 对象拷贝：设置publis动态数据
                BeanUtils.copyProperties(publish,vo);
                vo.setId(publish.getId().toString());
                vo.setImageContent(publish.getMedias().toArray(new String[]{}));

                // 根据用户id查询
                UserInfo userInfo = userInfoApi.findById(publish.getUserId());
                if (userInfo != null) {
                    // 对象拷贝：设置userInfo动态数据
                    BeanUtils.copyProperties(userInfo,vo);
                    if (userInfo.getTags() != null) {
                        vo.setTags(userInfo.getTags().split(","));
                    }
                }
                // 设置动态的用户id
                vo.setUserId(publish.getUserId());
                vo.setDistance("50米");
                // 设置时间
                vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(publish.getCreated())));
                vo.setHasLiked(0);
                vo.setHasLoved(0);
                voList.add(vo);
            }
        }
        // 设置vo集合
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }


    // 工具类：把publish转换为MovementsVo对象
    private void convertPublishToMovements(Publish publish, MovementsVo vo) {
        // 根据用户id查询
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo, vo);
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }
        }
        // 对象拷贝：publish-->vo
        BeanUtils.copyProperties(publish, vo);

        // 设置动态id、动态的图片
        vo.setId(publish.getId().toString());
        vo.setImageContent(publish.getMedias().toArray(new String[]{}));

        // 设置距离
        vo.setDistance("50米");
        // 设置时间如：5小时之前
        vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(publish.getCreated())));

        vo.setHasLiked(0);
        vo.setHasLoved(0);

    }

    /**
     * 接口名称：动态详情
     */
    public ResponseEntity<Object> findMovementsById(String publishId) {
        // 根据动态id查询
        Publish publish = publishApi.findById(publishId);
        // 创建返回的vo对象
        MovementsVo vo = new MovementsVo();
        // publish--->vo
        this.convertPublishToMovements(publish,vo);
        return ResponseEntity.ok(vo);
    }

    /**
     * 接口名称：评论列表翻页
     */
    public ResponseEntity<Object> findCommentsById(
            String publishId, Integer page, Integer pagesize) {
        //1. 分页查询评论
        PageResult pageResult = commentApi.findByPage(publishId, page, pagesize);
        //2. 获取评论数据
        List<Comment> list = (List<Comment>) pageResult.getItems();
        //3. 定义返回的vo集合
        List<CommentVo> voList = new ArrayList<>();
        //4. 封装数据 list--->voList
        if (!CollectionUtils.isEmpty(list)) {
            for (Comment comment : list) {
                CommentVo vo = new CommentVo();
                vo.setId(comment.getId().toString());
                // 根据用户id查询
                UserInfo userInfo = userInfoApi.findById(comment.getUserId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                vo.setContent(comment.getContent());
                vo.setCreateDate(new DateTime(comment.getCreated()).toString("yyyy年MM月dd日 HH:mm"));
                vo.setLikeCount(0);
                vo.setHasLiked(0);

                voList.add(vo);
            }
        }
        //5. 设置到分页对象中
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }




    /**
     * 接口名称：动态拒绝
     */
    public ResponseEntity<Object> rejectManage(String[] publshList) {
        for (String publishId : publshList) {
            publishApi.updateState(publishId,2);
        }
        return ResponseEntity.ok("message");
    }
    /**
     * 接口名称：动态通过
     */
    public ResponseEntity<Object> passManage(String[] publishList) {
        for (String publishId : publishList) {
            publishApi.updateState(publishId,1);
        }
        Map<String, String> map = new HashMap<>();
        map.put("message","操作成功");
        return ResponseEntity.ok(map);
    }
}



















